package com.sjb.cp.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import com.sjb.cp.annotation.AuthCheck;
import com.sjb.cp.api.aliyun.model.CreateOutPaintingTaskRequest;
import com.sjb.cp.api.aliyun.model.CreateOutPaintingTaskResponse;
import com.sjb.cp.api.aliyun.model.GetOutPaintingResponse;
import com.sjb.cp.api.aliyun.sub.AliYunAiApi;
import com.sjb.cp.common.BaseResponse;
import com.sjb.cp.common.DeleteRequest;
import com.sjb.cp.common.ResultUtils;
import com.sjb.cp.exception.BusinessException;
import com.sjb.cp.exception.ErrorCode;
import com.sjb.cp.exception.ThrowUtils;
import com.sjb.cp.manager.CosManager;
import com.sjb.cp.manager.auth.SpaceUserAuthManager;
import com.sjb.cp.manager.auth.StpKit;
import com.sjb.cp.manager.auth.annotation.SaSpaceCheckPermission;
import com.sjb.cp.model.constant.SpaceUserPermissionConstant;
import com.sjb.cp.model.constant.UserConstant;
import com.sjb.cp.model.enums.PictureReviewStatusEnum;
import com.sjb.cp.model.enums.SpaceLevelEnum;
import com.sjb.cp.model.enums.SpaceTypeEnum;
import com.sjb.cp.model.po.Picture;
import com.sjb.cp.model.po.Space;
import com.sjb.cp.model.po.User;
import com.sjb.cp.model.request.picture.*;
import com.sjb.cp.model.vo.PictureTagCategoryVo;
import com.sjb.cp.model.vo.PictureVO;
import com.sjb.cp.model.vo.SpaceLevelVo;
import com.sjb.cp.service.impl.PictureServiceImpl;
import com.sjb.cp.service.impl.SpaceServiceImpl;
import com.sjb.cp.service.impl.UserServiceImpl;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author:sjb
 * @CreateTime:2024-12-12
 * @Description: 文件操作相关视图
 * @Version：1.0
 */
@RestController
@RequestMapping("/picture")
@Slf4j
public class PictureController {

    @Resource
    private PictureServiceImpl pictureService;

    @Resource
    private UserServiceImpl userService;

    @Resource
    private SpaceServiceImpl spaceService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private AliYunAiApi aliYunAiApi;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;


    @PostMapping("/delete")
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        boolean deleted = pictureService.deletePicture(deleteRequest, request);
        return ResultUtils.success(deleted);
    }

    /**
     * 更新图片（仅管理员可用）
     */
    @PostMapping("/update")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    @AuthCheck(mustRole = UserConstant.MUST_ADMIN)
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest,
                                               HttpServletRequest request) {
        if (pictureUpdateRequest == null || pictureUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 将实体类和 DTO 进行转换
        Picture picture = new Picture();
        User loginUser = userService.getLoginUser(request);
        pictureService.fillReviewParams(picture, loginUser);
        BeanUtils.copyProperties(pictureUpdateRequest, picture);
        // 注意将 list 转为 string
        picture.setTags(JSONUtil.toJsonStr(pictureUpdateRequest.getTags()));
        // 数据校验
        pictureService.validPicture(picture);
        // 判断是否存在
        long id = pictureUpdateRequest.getId();
        Picture oldPicture = pictureService.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = pictureService.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取图片（仅管理员可用）
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.MUST_ADMIN)
    public BaseResponse<Picture> getPictureById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(picture);
    }

    /**
     * 根据 id 获取图片（封装类）
     */
    @GetMapping("/get/vo")
    public BaseResponse<PictureVO> getPictureVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        // 空间权限校验
        Long spaceId = picture.getSpaceId();
        Space space = null;
        if (spaceId != null){
            boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasPermission, ErrorCode.NO_AUTH_ERROR);
            space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR,"空间不存在");
        }
        User loginUser = userService.getLoginUser(request);
        List<String> permissionsList = spaceUserAuthManager.getPermissionsList(space, loginUser);
        PictureVO pictureVO = pictureService.getPictureVO(picture, request);
        pictureVO.setPermissions(permissionsList);
        // 获取封装类
        return ResultUtils.success(pictureVO);
    }

    /**
     * 分页获取图片列表（仅管理员可用）
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.MUST_ADMIN)
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest pictureQueryRequest) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        return ResultUtils.success(picturePage);
    }


    /**
     * 分页获取图片列表（封装类）
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PictureVO>> listPictureVoByPage(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                             HttpServletRequest request) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Long spaceId = pictureQueryRequest.getSpaceId();
        if (spaceId == null){
            // 允许查看已过审的数据
            pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getCode());
            pictureQueryRequest.setNullSpaceId(true);
        }else{
            // 私有空间
            User loginUser = userService.getLoginUser(request);
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null,ErrorCode.NOT_FOUND_ERROR,"空间不存在");
            if (!ObjectUtil.notEqual(space.getUserId(),loginUser.getId())){
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"无权访问私有空间");
            }
        }
        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        // 获取封装类
        return ResultUtils.success(pictureService.getPictureVOPage(picturePage, request));
    }


    @PostMapping("/list/page/cache")
    public BaseResponse<Page<PictureVO>> listPictureVoByCache(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                              HttpServletRequest request) {
        int current = pictureQueryRequest.getCurrent();
        int pageSize = pictureQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(pageSize > 20, ErrorCode.PARAMS_ERROR);

        pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getCode());
        // 构建缓存key
        String queryCondition = JSONUtil.toJsonStr(pictureQueryRequest);
        String hashHey = DigestUtils.md5DigestAsHex(queryCondition.getBytes());
        String redisKey = UserConstant.REDIS_KEY.LIST_PICTURE_CACHE + hashHey;
        // 从缓存中查询
        ValueOperations<String, String> stringValueOperations = stringRedisTemplate.opsForValue();
        String listPictureByCache = stringValueOperations.get(redisKey);
        if (listPictureByCache != null) {
            Page<PictureVO> listPicturePage = JSONUtil.toBean(listPictureByCache, Page.class);
            return ResultUtils.success(listPicturePage);
        }
        // 查库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, pageSize),
                pictureService.getQueryWrapper(pictureQueryRequest));
        // 获取封装类
        Page<PictureVO> pictureVoPage = pictureService.getPictureVOPage(picturePage, request);
        // 存入缓存
        String cacheValue = JSONUtil.toJsonStr(pictureVoPage);
        int expireTime = 300 + RandomUtil.randomInt(0, 300);
        stringValueOperations.set(redisKey, cacheValue, expireTime, TimeUnit.SECONDS);
        return ResultUtils.success(pictureVoPage);
    }


    /**
     * 编辑图片（给用户使用）
     */
    @PostMapping("/edit")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest pictureEditRequest, HttpServletRequest request) {
        boolean edited = pictureService.editPicture(pictureEditRequest, request);
        return ResultUtils.success(edited);
    }

    @GetMapping("/tag_category")
    public BaseResponse<PictureTagCategoryVo> listPictureTagCategory() {
        PictureTagCategoryVo pictureTagCategory = new PictureTagCategoryVo();
        List<String> tagList = Arrays.asList("热门", "搞笑", "生活", "高清", "艺术", "校园", "背景", "简历", "创意");
        List<String> categoryList = Arrays.asList("模板", "电商", "表情包", "素材", "海报");
        pictureTagCategory.setTagList(tagList);
        pictureTagCategory.setCategoryList(categoryList);
        return ResultUtils.success(pictureTagCategory);
    }

    @PostMapping("/reviewPictureStatus")
    @AuthCheck(mustRole = UserConstant.MUST_ADMIN)
    public BaseResponse<Boolean> reviewPictureStatus(@RequestBody PictureReviewRequest pictureReviewRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(pictureReviewRequest == null, ErrorCode.PARAMS_ERROR);

        User loginUser = userService.getLoginUser(request);
        pictureService.doReviewPicture(pictureReviewRequest, loginUser);
        return ResultUtils.success(true);
    }

    @PostMapping("/upload/url")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    public BaseResponse<PictureVO> uploadPictureByUrl(PictureUploadRequest pictureUploadRequest,
                                                      HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        String fileUrl = pictureUploadRequest.getFileUrl();
        PictureVO pictureVO = pictureService.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }

    @PostMapping("/upload/batch")
    @AuthCheck(mustRole = UserConstant.MUST_ADMIN)
    public BaseResponse<Integer> uploadPictureByBatch(@RequestBody PictureUploadByBatchRequest pictureUploadByBatchRequest,
                                                      HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        Integer byBatch = pictureService.uploadPictureByBatch(pictureUploadByBatchRequest, loginUser);
        return ResultUtils.success(byBatch);
    }

    @GetMapping("/space/level")
    public BaseResponse<List<SpaceLevelVo>> getSpaceLevel(){
        List<SpaceLevelVo> spaceLevelVoList = Arrays.stream(SpaceLevelEnum.values())
                .map(spaceLevelEnum -> new SpaceLevelVo(
                        spaceLevelEnum.getValue(),
                        spaceLevelEnum.getText(),
                        spaceLevelEnum.getMaxCount(),
                        spaceLevelEnum.getMaxSize())).collect(Collectors.toList());
        return ResultUtils.success(spaceLevelVoList);
    }

    @PostMapping("/picture/searchPictureByColor")
    public BaseResponse<List<PictureVO>> searchPictureByColor(SearchPictureByColorRequest pictureByColorRequest,
                                                              HttpServletRequest request){
        ThrowUtils.throwIf(pictureByColorRequest == null,ErrorCode.PARAMS_ERROR,"请求参数为空");
        User loginUser = userService.getLoginUser(request);
        List<PictureVO> result = pictureService.searchPictureByColor(pictureByColorRequest.getPicColor(),
                pictureByColorRequest.getSpaceId(), loginUser);
        return ResultUtils.success(result);
    }

    @PostMapping("/edit/editBatch")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPictureBatch(@RequestBody PictureEditByBatchRequest pictureEditByBatchRequest,
                                               HttpServletRequest request){
        ThrowUtils.throwIf(pictureEditByBatchRequest == null,ErrorCode.PARAMS_ERROR,"参数为空");
        pictureService.editPictureByBatch(pictureEditByBatchRequest,request);
        return ResultUtils.success(true);
    }

    /**
     * 请求创建图片编辑任务
     * @param outPaintingAIRequest
     * @param request
     * @return
     */
    @PostMapping("/out_painting/create_task")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<CreateOutPaintingTaskResponse> createOutPaintingTask(@RequestBody OutPaintingAIRequest outPaintingAIRequest,
                                                                             HttpServletRequest request){
        ThrowUtils.throwIf(outPaintingAIRequest == null,ErrorCode.PARAMS_ERROR,"请求参数为空");
        User loginUser = userService.getLoginUser(request);
        CreateOutPaintingTaskResponse outPaintingTask = pictureService.createOutPaintingTask(outPaintingAIRequest, loginUser);
        return ResultUtils.success(outPaintingTask);
    }

    /**
     * 查询图片编辑任务
     * @param taskId
     * @return
     */
    @GetMapping("/get/out_painting_task")
    public BaseResponse<GetOutPaintingResponse> getOutPaintingResponseBaseResponse(String taskId){
        ThrowUtils.throwIf(taskId == null,ErrorCode.PARAMS_ERROR,"任务ID为空");
        GetOutPaintingResponse outPaintingResponse = aliYunAiApi.getOutPaintingStatus(taskId);
        return ResultUtils.success(outPaintingResponse);
    }

}
